// eslint-disable-next-line no-use-before-define
import React, { useState } from "react";
import { Button, Modal, Input } from "antd";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import Item from "./item";
import AddInput from "@/components/func/add-input";
import { updateQrGroup, updateQrGroupOrder, removeQrGroup } from "@/assets/js/networkRequest/method";

// 组件需要的参数
interface Props {
  total: number;
  defaultGroup: any; // 默认分组信息
  listGroupData: any; // 分组信息
  initQrGroupData: (newListData: any) => void; // 将新的分组进行初始化函数
  addGroup: (name: string) => void; // 添加分组函数
}

interface updateNameOrOrderProps {
  id: number;
  name?: string;
  order?: number;
}
// 选中
let selectedId: any = -1;

const ContentLeft = ({
  total,
  defaultGroup,
  listGroupData,
  initQrGroupData,
  addGroup,
}: Props) => {
  console.log(defaultGroup, listGroupData);

  const [, setRender] = useState(0);
  const [visible, setVisible] = useState(false);
  const [updateName, setUpdateName] = useState("");
  const [updateData, setUpdateDate] = useState({ type: "", item: null }); // type : update 修改  delate ： 删除;  item： 操作的对象

  /* 拖拽过程排序处理 */
  const handleDND = (dragIndex: React.ReactText, hoverIndex: any) => {
    let tmp = listGroupData[Number(dragIndex)]; // 临时储存文件
    listGroupData.splice(Number(dragIndex), 1); // 移除拖拽项
    listGroupData.splice(hoverIndex, 0, tmp); // 插入放置项
    setRender(Math.random() + 1);
  };

  /* 选择指定分组列表 */
  const selectedList = (id: number, name: string) => {
    if (selectedId === id) {
      return;
    }
    window.globalState.muState("listData", name === "全部" ? 0 : id);
    selectedId = id;
    setRender(Math.random() + 1);
  };

  /* 点击更新或者删除，弹窗需要的值 */
  const updateAndDel = ({ type, item }: { type: string; item: any }) => {
    setUpdateName(item.name);
    setUpdateDate({ type, item });
    setVisible(true);
  };

  /* 拖拽结束请求排序接口 */
  const dragEnd = async () => {
    let res = await updateQrGroupOrder({
      groupid_sort_list: listGroupData.map((item: any) => item.id),
    });
    console.log(res);
    console.log(listGroupData.map((item: any) => item.id));
  };

  /* 更新或者删除操作 */
  const requestUpdateAndDel = async () => {
    let {
      item: { id, order },
    }: any = updateData;
    if (updateData.type === "update") {
      let data: any = await updateQrGroup({
        groupid: id,
        name: updateName,
        order: order,
      });
      if (data.code === 200) {
        updateNameOrOrder({ id, name: updateName });
      }
    } else {
      let data: any = await removeQrGroup({ groupid: [id.toString()] });
      if (data.code === 200) {
        listGroupData = listGroupData.filter((item: any) => item.id !== id);
        selectedList(0, "全部");
      }
    }
    initQrGroupData(listGroupData);
    setVisible(false);
  };

  /* 修改名字或者顺序 */
  const updateNameOrOrder = ({ id, name = "", order }: updateNameOrOrderProps) => {
    listGroupData.map((item: any) => {
      if (item.id === id) {
        item.name = name || item.name;
        item.order = order || item.order;
      }
    });
  };

  return (
    <div className="qr-content-left flex flex-col w-220 mr-8 h-full bg-white rounded-sm">
      <AddInput
        addName="添加分组"
        placeholder="名称"
        length={10}
        icon="icon-tianjia"
        onPressEnter={(e: string) => {
          addGroup(e);
        }}
      />
      <div className="flex-1 pb-10 overflow-y-auto mt-10 scrollY">
        {/* 全部和默认列表 */}
        <ul>
          <li
            className={`hover:bg-blue-effaff cursor-pointer w-full pr-22 pl-24 px-0 ${
              selectedId === -1 ? "active" : ""
            }`}
            onClick={() => {
              selectedList(-1, "全部");
            }}>
            <p className="flex justify-between items-center p-0 h-40 w-full m-0 text-grey-800">
              <span>全部</span>
              <span className="text-grey-300">{total}</span>
            </p>
          </li>
          <li
            className={`hover:bg-blue-effaff cursor-pointer w-full pr-22 pl-24 p-0 ${
              selectedId === defaultGroup.id ? "active" : ""
            }`}
            onClick={() => {
              selectedList(defaultGroup.id, "默认分组");
            }}>
            <p className="flex justify-between items-center h-40 text-grey-800">
              <span>默认分组</span>
              <span className=" text-grey-300">{defaultGroup && defaultGroup.count}</span>
            </p>
          </li>
        </ul>

        {/* 子列表 */}
        <DndProvider backend={HTML5Backend}>
          <ul>
            {listGroupData.length > 0 &&
              listGroupData.map((item: any, i: any) => {
                return (
                  <Item
                    key={item.id}
                    index={i}
                    data={item}
                    moveCard={handleDND}
                    updateAndDel={updateAndDel}
                    dragEnd={dragEnd}
                    onClick={() => {
                      selectedList(item.id, item.name);
                    }}
                    classname={`group hover:bg-blue-effaff cursor-pointer w-full pr-22 pl-24 px-0 relative ${
                      selectedId === item.id ? "active" : ""
                    }`}
                  />
                );
              })}
          </ul>
        </DndProvider>
      </div>

      {/* 修改或者删除窗口 */}
      <Modal
        closable={false}
        maskClosable={false}
        visible={visible}
        width={updateData.type === "" ? 634 : 400}
        footer={null}
        onCancel={() => {
          setVisible(false);
        }}>
        <h2 className="dialog-title">
          {updateData.type === "update" ? "修改名称" : "删除分组"}
        </h2>

        {updateData.type === "update" ? (
          <div className="flex items-center relative justify-center">
            <span className="w-106 text-right mr-16">修改名称:</span>
            <Input
              value={updateName}
              defaultValue={updateName}
              maxLength={10}
              autoFocus
              onChange={(e: any) => {
                setUpdateName(e.target.value);
              }}
            />
          </div>
        ) : (
          <div className="flex items-center relative justify-start">
            <p>{`是否确认删除「${updateName}」分组？`}</p>
          </div>
        )}

        <div className="btn-wrap">
          <div className="left"></div>
          <div className="right">
            <Button
              onClick={() => {
                setVisible(false);
              }}>
              取消
            </Button>
            <Button
              type="primary"
              onClick={() => {
                requestUpdateAndDel();
              }}>
              {updateData.type === "update" ? "修改" : "删除"}
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default ContentLeft;
